package com.ada.base.security.service.impl;

import com.ada.base.security.CurrentUserContext;
import com.ada.base.security.entity.res.AuthorityRes;
import com.ada.base.security.service.AuthorityService;
import com.ada.base.security.entity.Authority;
import com.ada.base.security.util.TreeUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapperResultSetExtractor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class AuthorityServiceImpl implements AuthorityService {
    private JdbcTemplate jdbcTemplate;

    public AuthorityServiceImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public List<Authority> findAuthorityByUserId(Integer userId) {
        return null;
    }

    @Override
    public Authority findByUrlAndMethod(String url, String method) {
        String sql = "select url,method,code from authority where url = ? and method = ?";
        List<Authority> authorities = jdbcTemplate.query(sql, new Object[]{url, method}, new RowMapperResultSetExtractor<>(new BeanPropertyRowMapper<>(Authority.class), 1));
        if (CollectionUtils.isEmpty(authorities))
            return null;
        return authorities.get(0);
    }

    @Override
    public List<AuthorityRes> authorityList() {
        String sql = "select * from authority where clientId=?";
        List<AuthorityRes> query = jdbcTemplate.query(sql, new Object[]{CurrentUserContext.clientId()}, new RowMapperResultSetExtractor<>(new BeanPropertyRowMapper<>(AuthorityRes.class), 1));
        return TreeUtils.listToTree(query);
    }

    @Override
    public List<AuthorityRes> findAuthorityByRoleId(long roleId) {
        String sql = "select a.* from authority a inner join role_authority b on a.id = b.authorityId where b.roleId = ?";
        List<AuthorityRes> query = jdbcTemplate.query(sql, new Object[]{roleId}, new RowMapperResultSetExtractor<>(new BeanPropertyRowMapper<>(AuthorityRes.class), 1));
        return TreeUtils.listToTree(query);
    }
}
